package com.hskn.hss.module.inspectionCfg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.module.costdict.service.ICostDictService;
import com.hskn.hss.module.costdictitem.entity.CostDictItem;
import com.hskn.hss.module.costdictitem.mapper.CostDictItemMapper;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.inspectionCfg.entity.TlInspectionCfg;
import com.hskn.hss.module.inspectionCfg.mapper.TlInspectionCfgMapper;
import com.hskn.hss.module.inspectionCfg.service.ITlInspectionCfgService;
import com.hskn.hss.module.inspectionCfg.to.*;
import com.hskn.hss.module.inspectionCfg.vo.TlInspectionCfgDetailVO;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.AttributeUtils;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-06
 */
@Service
public class TlInspectionCfgServiceImpl extends ServiceImpl<TlInspectionCfgMapper, TlInspectionCfg> implements ITlInspectionCfgService {

    @Resource
    TlInspectionCfgMapper tlInspectionCfgMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Resource
    ITlCarService carService;
    @Resource
    ITlCarTypeService carTypeService;
    @Resource
    ISysDepartService departService;
    @Resource
    IUserService userService;
    @Resource
    UserMapper userMapper;
    @Resource
    ICostDictService costDictService;
    @Resource
    CostDictItemMapper costDictItemMapper;
    @Resource
    private SysDepartMapper departMapper;
    @Resource
    private TlCarMapper carMapper;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public int insert(InsertTlInspectionCfgTO insertTlInspectionCfgTO) {

        String uid = LoginUtils.getUser().getUid();
        TlInspectionCfg tlInspectionCfg = JSONObject.parseObject(JSONObject.toJSONString(insertTlInspectionCfgTO), TlInspectionCfg.class);
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();
        tlInspectionCfg.setCreatby(uid);
        tlInspectionCfg.setCreattime(new Date());
        tlInspectionCfg.setId(StringUtils.uuid());
        tlInspectionCfg.setDeptid(deptid);
        TlCar car = null;
        if (tlInspectionCfg != null) {
            car = carService.getById(tlInspectionCfg.getCarnumid());
            tlInspectionCfg.setCartype(car.getCartypeid());
            tlInspectionCfg.setDeptidforcar(car.getCardeptid());
            tlInspectionCfg.setDeptid(car.getCardeptid());
        }
        tlInspectionCfg.setId(StringUtils.uuid());
        return tlInspectionCfgMapper.insert(tlInspectionCfg);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public int update(UpdateTlInspectionCfgTO updateTlInspectionCfgTO) {

        String uid = LoginUtils.getUser().getUid();
        TlInspectionCfg tlInspectionCfg = JSONObject.parseObject(JSONObject.toJSONString(updateTlInspectionCfgTO), TlInspectionCfg.class);
        tlInspectionCfg.setUpdateby(uid);
        tlInspectionCfg.setUpdatetime(new Date());
        TlCar car = null;
        if (tlInspectionCfg != null) {
            car = carService.getById(tlInspectionCfg.getCarnumid());
            tlInspectionCfg.setCartype(car.getCartypeid());
            tlInspectionCfg.setDeptidforcar(car.getCardeptid());
            tlInspectionCfg.setDeptid(car.getCardeptid());
        }
        return tlInspectionCfgMapper.updateById(tlInspectionCfg);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public int deleteByid(ForIdsTO forIdsTO) {
        return tlInspectionCfgMapper.deleteBatchIds(forIdsTO.getIds());
    }

    @Override
    public List<TlInspectionCfg> selectList(QueryWrapper<TlInspectionCfg> queryWrapper) {
        return tlInspectionCfgMapper.selectList(queryWrapper);
    }

    @Override
    public void excelReader(List<TlInspectionCfg> inspectionCfgList) throws ExcelReaderDataException {

        String uid = LoginUtils.getUser().getUid();
        List<SysDepart> departList = departMapper.selectList(new QueryWrapper<>());
        List<CostDictItem> costDictItemList = costDictItemMapper.selectList(new QueryWrapper<>());
        List<TlCar> carList = carMapper.selectList(new QueryWrapper<>());
        Map<String, TlCar> carMap = new HashMap<>();
        if (!carList.isEmpty()) {
            carMap = carList.stream().collect(Collectors.groupingBy(TlCar::getCarnumber, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
        }
        Map<String, SysDepart> departMap = new HashMap<>();
        if (!departList.isEmpty()) {
            Predicate<SysDepart> departNameNotNull = depart -> StringUtils.isNotEmpty(depart.getDepartName());
            departList = departList.stream().filter(departNameNotNull).collect(Collectors.toList());
            departMap = GroupingByUtils.getGroupingForMapEntity(departList, SysDepart::getDepartName, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        Map<String, CostDictItem> costDictItemMap = new HashMap<>();
        if (!costDictItemList.isEmpty()) {
            Predicate<CostDictItem> nameNotNull = costDictItem -> StringUtils.isNotEmpty(costDictItem.getCostname());
            costDictItemList = costDictItemList.stream().filter(nameNotNull).collect(Collectors.toList());
            costDictItemMap = GroupingByUtils.getGroupingForMapEntity(costDictItemList, CostDictItem::getCostname, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        Map<String, User> userMap = new HashMap<>();
        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        userMap = GroupingByUtils.getGroupingForMapEntity(userList, User::getName, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        int num = 1;
        String str = "";
        for (TlInspectionCfg inspectionCfg : inspectionCfgList) {
            inspectionCfg.setCreattime(new Date());
            inspectionCfg.setCreatby(uid);
            if (StringUtils.isNotEmpty(inspectionCfg.getCarCardNum())) {
                if (carMap.containsKey(inspectionCfg.getCarCardNum())) {
                    inspectionCfg.setCarnumid(carMap.get(inspectionCfg.getCarCardNum()).getId());
                } else {
                    str += "第" + num + "条的" + "“‘" + "车牌号’:‘" + inspectionCfg.getCarCardNum() + "’”" + "不存在;##";
                }
            } else {
                str += "第" + num + "条的“车牌号”不能为空;##";
            }
            if (departMap.containsKey(inspectionCfg.getDeptName())) {
                inspectionCfg.setDeptid(departMap.get(inspectionCfg.getDeptName()).getId());
                inspectionCfg.setDeptidforcar(departMap.get(inspectionCfg.getDeptName()).getId());
            } else {
                str += "第" + num + "条的" + "“‘" + "所属机构’:‘" + inspectionCfg.getDeptName() + "’”" + "不存在;##";
            }
            if (Objects.isNull(inspectionCfg.getCosttime())) {
                str += "第" + num + "条的’年检日期‘时间格式不正确;##";
            }
            if (Objects.isNull(inspectionCfg.getTotalcost())) {
                str += "第" + num + "条的“总费用”不能为空;##";
            }
            if (costDictItemMap.containsKey(inspectionCfg.getRepairreasonName())) {
                inspectionCfg.setRepairreason(costDictItemMap.get(inspectionCfg.getRepairreasonName()).getId());
            } else {
                str += "第" + num + "条的" + "“‘" + "年检项目’:‘" + inspectionCfg.getRepairreasonName() + "’”" + "不存在;##";
            }
            if (!userMap.containsKey(inspectionCfg.getPayusername())) {
                str += "第" + num + "条的" + "“‘" + "缴费人’:‘" + inspectionCfg.getPayusername() + "’”" + "不存在;##";
            }

            num++;
        }
        if (StringUtils.isNotEmpty(str)) {
            throw new ExcelReaderDataException("您导入的数据:##" + str);
        }
    }

    @Override
    public TlInspectionCfgDetailVO getDetailById(TlInspectionCfgTOForOnlyId inspectionCfgTOForOnlyId) {
        String id = inspectionCfgTOForOnlyId.getId();
        TlInspectionCfg tlInspectionCfg = tlInspectionCfgMapper.selectById(id);
        TlCar car = null;
        TlCarType carType = null;
        SysDepart depart = null;
        User user = null;
        CostDictItem costDictItem = null;

        if (tlInspectionCfg != null) {
            car = carService.getById(tlInspectionCfg.getCarnumid());
            depart = departService.getById(tlInspectionCfg.getDeptid());
            costDictItem = costDictItemMapper.selectById(tlInspectionCfg.getRepairreason());

        }
        if (car != null) {
            carType = carTypeService.getById(car.getCartypeid());
            user = userService.getById(car.getDriverid());
            tlInspectionCfg.setCarCardNum(car.getCarnumber());
        }
        if (carType != null) {
            tlInspectionCfg.setCarTyeName(carType.getTypename());
        }
        if (depart != null) {
            tlInspectionCfg.setDeptName(depart.getDepartName());
        }
        if (user != null) {
            tlInspectionCfg.setDriverName(user.getName());
        }
        if (costDictItem != null) {
            tlInspectionCfg.setRepairreasonName(costDictItem.getCostname());
        }
        TlInspectionCfgDetailVO inspectionCfgDetailVO = JSONObject.parseObject(JSONObject.toJSONString(tlInspectionCfg), TlInspectionCfgDetailVO.class);
        return inspectionCfgDetailVO;
    }

    @Override
    @DataScope(deptAlias = "deptidforcar", userAlias = "creatBy")
    public List<TlInspectionCfg> getTlInspectionCfgList(InspectionCfgListTO inspectionCfgListTo, SimpleDateFormat format) throws ParseException {
        QueryWrapper<TlInspectionCfg> inspectionCfgQueryWrapper = new QueryWrapper<>();
        if (inspectionCfgListTo.getParams().containsKey("dataScope") && StringUtils.isNotEmpty(inspectionCfgListTo.getParams().get("dataScope").toString())) {
            inspectionCfgQueryWrapper.lambda().apply(inspectionCfgListTo.getParams().get("dataScope").toString());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListTo.getDeptid())) {
            inspectionCfgQueryWrapper.lambda().eq(TlInspectionCfg::getDeptid, inspectionCfgListTo.getDeptid());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListTo.getCarNumid())) {
            inspectionCfgQueryWrapper.lambda().eq(TlInspectionCfg::getCarnumid, inspectionCfgListTo.getCarNumid());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListTo.getOrderNo())) {
            inspectionCfgQueryWrapper.lambda().eq(TlInspectionCfg::getOrderNo, inspectionCfgListTo.getOrderNo());
        }
        if (inspectionCfgListTo.getIds() != null && !inspectionCfgListTo.getIds().isEmpty()) {
            inspectionCfgQueryWrapper.lambda().in(TlInspectionCfg::getId, inspectionCfgListTo.getIds());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListTo.getStartTime()) && StringUtils.isNotEmpty(inspectionCfgListTo.getEndTime())) {
            inspectionCfgQueryWrapper.lambda().ge(TlInspectionCfg::getCosttime, format.parse(inspectionCfgListTo.getStartTime()));
            inspectionCfgQueryWrapper.lambda().le(TlInspectionCfg::getCosttime, format.parse(inspectionCfgListTo.getEndTime()));
        }
        List<TlInspectionCfg> inspectionCfgList = tlInspectionCfgMapper.selectList(inspectionCfgQueryWrapper);
        return inspectionCfgList;
    }

    @Override
    @DataScope(deptAlias = "deptidforcar", userAlias = "creatBy")
    public TableDataInfo getList(InspectionCfgListForPageTO inspectionCfgListForPageTO) throws ParseException {
        //查询数据
        QueryWrapper<TlInspectionCfg> inspectionCfgQueryWrapper = new QueryWrapper<>();
        if (inspectionCfgListForPageTO.getParams().containsKey("dataScope") && StringUtils.isNotEmpty(inspectionCfgListForPageTO.getParams().get("dataScope").toString())) {
            inspectionCfgQueryWrapper.lambda().apply(inspectionCfgListForPageTO.getParams().get("dataScope").toString());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListForPageTO.getDeptid())) {
            inspectionCfgQueryWrapper.lambda().eq(TlInspectionCfg::getDeptid, inspectionCfgListForPageTO.getDeptid());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListForPageTO.getCarNumid())) {
            inspectionCfgQueryWrapper.lambda().eq(TlInspectionCfg::getCarnumid, inspectionCfgListForPageTO.getCarNumid());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListForPageTO.getOrderNo())) {
            inspectionCfgQueryWrapper.lambda().eq(TlInspectionCfg::getOrderNo, inspectionCfgListForPageTO.getOrderNo());
        }
        if (inspectionCfgListForPageTO.getIds() != null && !inspectionCfgListForPageTO.getIds().isEmpty()) {
            inspectionCfgQueryWrapper.lambda().in(TlInspectionCfg::getId, inspectionCfgListForPageTO.getIds());
        }
        if (StringUtils.isNotEmpty(inspectionCfgListForPageTO.getStartTime()) && StringUtils.isNotEmpty(inspectionCfgListForPageTO.getEndTime())) {
            inspectionCfgQueryWrapper.lambda().between(TlInspectionCfg::getCosttime, AttributeUtils.timeCompletion(inspectionCfgListForPageTO.getStartTime(), 's'), AttributeUtils.timeCompletion(inspectionCfgListForPageTO.getEndTime(), 'e'));
        }
        inspectionCfgQueryWrapper.lambda().orderByDesc(TlInspectionCfg::getCreattime);
        List<TlInspectionCfg> list = tlInspectionCfgMapper.selectList(inspectionCfgQueryWrapper);
        Map<String, User> userMap = userService.getUserMap();
        Map<String, TlCar> carMap = carService.getCarMap(new QueryWrapper<>());
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, TlCarType> carTypeMap = carTypeService.getCarTypeMap(new QueryWrapper<>());
        Map<String, CostDictItem> costDictItemMap = costDictService.getitemForCostDictItemMap(new QueryWrapper<>());
        for (TlInspectionCfg tlInspectionCfg : list) {
            if (carMap != null && carMap.containsKey(tlInspectionCfg.getCarnumid())) {
                tlInspectionCfg.setCarCardNum(carMap.get(tlInspectionCfg.getCarnumid()).getCarnumber());
            }
            if (userMap != null && userMap.containsKey(tlInspectionCfg.getDeptid())) {
                tlInspectionCfg.setDriverName(userMap.get(tlInspectionCfg.getDriverid()).getName());
            }
            if (carTypeMap != null && carTypeMap.containsKey(tlInspectionCfg.getCartype())) {
                tlInspectionCfg.setCarTyeName(carTypeMap.get(tlInspectionCfg.getCartype()).getTypename());
            }
            if (departMap != null && departMap.containsKey(tlInspectionCfg.getDeptid())) {
                tlInspectionCfg.setDeptName(departMap.get(tlInspectionCfg.getDeptid()).getDepartName());
            }
            if (costDictItemMap != null && costDictItemMap.containsKey(tlInspectionCfg.getRepairreason())) {
                tlInspectionCfg.setRepairreasonName(costDictItemMap.get(tlInspectionCfg.getRepairreason()).getCostname());
            }
            if (Objects.nonNull(tlInspectionCfg.getCosttime())) {
                tlInspectionCfg.setCosttimeString(Tools.getYearMonthDayString(tlInspectionCfg.getCosttime()));
            }
        }
        return Tools.buildTableDataInfo(inspectionCfgListForPageTO.getPage(), inspectionCfgListForPageTO.getSize(),list);
    }
}
